import { type GoGoAST } from "gogocode";
import { CommonParams, IGoGoNodeAttr } from "../../types";
import { updateLocalesFile } from "../../utils/file";
import { hasChinese } from "../../utils/check";

/**
 * 处理绑定值
 * @param sfcAst SFC的AST
 * @param CONFIG 配置
 * @param logger 日志处理器
 * @param filePath 文件路径
 * @returns AST
 */
const handleVBind = ({
  sfcAst,
  CONFIG,
  logger,
  filePath,
}: CommonParams & { sfcAst: GoGoAST }): GoGoAST => {
  const { I18N_FUNC, CHINESE_REGEX: CRG } = CONFIG;
  const getKey = (text: string) =>
    updateLocalesFile({
      text,
      CONFIG,
      logger,
      filePath,
    });
  return sfcAst
    .find(`<template></template>`)
    .find(`<$_$ $$$0></$_$>`)
    .each((item) => {
      // 处理属性
      const attrs = item.match["$$$0"] as unknown as IGoGoNodeAttr[];
      attrs.forEach((attr) => {
        const { key, value } = attr;
        if (value && hasChinese(value.content)) {
          const prop = key.content;
          const val = value.content;
          if (prop.startsWith(":") || prop.startsWith("v-bind:")) {
            const REG = new RegExp(`(\\'|\\")([\\w${CRG}]+?)\\1`);
            value.content = val
              .replace(REG, (_, p1, p2) => {
                const keyVal = getKey(p2);
                return `${CONFIG.I18N_FUNC}(${p1}${keyVal}${p1})`;
              })
              .replace(/(\`)([\S\s]+?)\1/, (_, __, p2: string) => {
                const obj: Record<string, unknown> = {};
                let i = 0;
                const str = p2.replace(/\$\{([\S\s]+?)\}/g, (...args) => {
                  const [_, p1] = args;
                  obj[i] = p1;
                  const objKey = i;
                  i++;
                  return `{${objKey}}`;
                });
                const key = getKey(str);
                const paramsStr = Object.entries(obj)
                  .map(([key, value]) => {
                    if (value === key) {
                      return key;
                    } else {
                      return `${key}:${value}`;
                    }
                  })
                  .join(",");
                return `${CONFIG.I18N_FUNC}('${key}',{${paramsStr}})`;
              });
          }
        }
      });
    })
    .root();
};

export default handleVBind;
